#!/usr/bin/env ruby

# <bitbar.title>Freshdesk</bitbar.title>
# <bitbar.author>Sean Stewart</bitbar.author>
# <bitbar.author.github>theseanstewart</bitbar.author.github>
# <bitbar.image>http://i.imgur.com/EqWSeUP.png</bitbar.image>
# <bitbar.dependencies>Ruby</bitbar.dependencies>
# <bitbar.desc>Shows open Freshesk tickets count</bitbar.desc>

# Configurations
FRESHDESK_SUBDOMAIN = ""
FRESHDESK_API_KEY = ""

require 'net/http'
require 'json'
require 'date'

def fetch_tickets()
  uri = URI("https://#{FRESHDESK_SUBDOMAIN}.freshdesk.com/api/v2/tickets?filter=new_and_my_open")
  req = Net::HTTP::Get.new(uri)
  req.basic_auth FRESHDESK_API_KEY, 'x'
  res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
  JSON.parse(res.body)
rescue
  []
end

def get_color(count)
  if count > 0
    return "color=red"
  end

  return ""
end

def get_image(count)

  if count > 0
    return "image=iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR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6llbE8AJlyMGV2MqQL6FQKOoGzeM3SvAG3+84nm18skHvUY6XGESv+ib4M35qFj2an1vH5k8anmEA05qRDTlBM8Jo0i2+RTeO/MsyK+pALhbQ7nxmAh9j3Ol1oki3HddC0uyKKnTRDl7p9R42Mez74kJ80E7G7RGyQZ7bUM3o4oIUw81CP4r1/swGhdV4jg293kU0xc4lNMePTi9mgyawhjos68MhnauvviDTz3dWf4AVG7SPEbQhiVUdwF+Yc0LMLjag3umNcRiT/mdtCZV6LLoU9r8yY6gi6HpGthq1c+Zh3dLqbitzFy120P6gUzzVXKq0O6nqG57oeNw4kP7qwyJeK+xCT/+ldnEK5//8Ht3XD9tfAQYAOuxnKfg3floAAAAASUVORK5CYII="
end

begin
  tickets = fetch_tickets

  count = 0

  if tickets.length > 0
    count = tickets.length
  end

  puts "#{tickets.length}" + " | " + get_color(count) + " " + get_image(count)

  puts "---"

  puts "View Tickets | href=https://#{FRESHDESK_SUBDOMAIN}.freshdesk.com/helpdesk/tickets"

rescue StandardError => msg
  puts 'Error occured, please refresh bitbar! >' + msg.to_s
end
